package com.dpp.dbase.db;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Build;
import android.os.Environment;
import android.util.Log;

import androidx.annotation.RawRes;
import androidx.annotation.RequiresApi;

import com.dpp.dbase.annotation.IgnoreField;
import com.dpp.dbase.annotation.TableField;
import com.dpp.dbase.annotation.TableName;
import com.dpp.dbase.api.PdParent;
import com.dpp.dbase.callback.MyCallBack;
import com.dpp.dbase.result.PdResult;
import com.dpp.dbase.utils.PdMethod;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

/**
 * db操作类，增删改
 * 2025年3月13日18:29:38：后续增加查询总数（count）,分组查询等功能
 */
public class PdOptDb extends PdParent {

    private static PdOptDb instance;

    public static PdOptDb getInstance() {
        if (instance == null) {
            instance = new PdOptDb();
        }
        return instance;
    }

    /**
     * 加载DB的数据库
     *
     * @param dbPath
     * @param dbName
     * @param dbVersion
     * @param context
     * @param id
     * @return
     */
    public SQLiteDatabase getSQLiteDatabase(String dbPath, String dbName, int dbVersion, Context context, @RawRes int id) {
        return super.getSQLiteDatabase(dbPath, dbName, dbVersion, context, id);
    }

    /**
     * 数据库备份或者恢复
     *
     * @param dbPath     当前数据库路径
     * @param backDbPath 需要备份到的数据库路径
     * @return
     */
    public PdResult backDb(String dbPath, String backDbPath) {
        return super.backDb(dbPath, backDbPath);
    }


    /**
     * ------------------------------------------增加开始---------------------------------------------
     */
    /**
     * 新增数据
     *
     * @param dbName
     * @param values
     * @param sqLiteOpenHelper
     * @return
     */
    public PdResult addDb(SQLiteDatabase sqLiteOpenHelper, String dbName, ContentValues values) {
        try {
            semaphore.acquire();
        } catch (InterruptedException e) {
            e.printStackTrace();
            return PdResult.Fail("新增失败：" + e.getMessage());
        }
        sqLiteOpenHelper.beginTransaction(); // 开始事务
        try {
            long insert = sqLiteOpenHelper.insert(dbName, null, values);
            if (insert > 0) {
                sqLiteOpenHelper.setTransactionSuccessful();// 标记事务成功
                //记录日志
                addLog(values, sqLiteOpenHelper, dbName);
                return PdResult.success();
            } else {
                //抛出异常回滚事务
                return PdResult.Fail("新增失败");
            }
        } catch (Exception e) {
            // 如果出现异常，事务将被回滚
            e.printStackTrace();
            return PdResult.Fail("新增失败：" + e.getMessage());
        } finally {
            sqLiteOpenHelper.endTransaction();// 结束事务
            semaphore.release();
        }
    }


    /**
     * 批量新增数据
     *
     * @param dbName
     * @param values
     * @param sqLiteOpenHelper
     * @return
     */
    public PdResult addDb(SQLiteDatabase sqLiteOpenHelper, String dbName, List<ContentValues> values) {
        try {
            semaphore.acquire();
        } catch (InterruptedException e) {
            e.printStackTrace();
            return PdResult.Fail("新增失败：" + e.getMessage());
        }
        sqLiteOpenHelper.beginTransaction(); // 开始事务
        try {
            int sum = 0;
            for (ContentValues contentValues : values) {
                long insert = sqLiteOpenHelper.insert(dbName, null, contentValues);
                if (insert > 0) {
                    //记录日志
                    addLog(contentValues, sqLiteOpenHelper, dbName);
                    sum++;
                }
            }
            if (sum == values.size()) {
                sqLiteOpenHelper.setTransactionSuccessful();// 标记事务成功
                return PdResult.success();
            } else {
                //抛出异常回滚事务
                return PdResult.Fail("新增失败");
            }
        } catch (Exception e) {
            // 如果出现异常，事务将被回滚
            e.printStackTrace();
            return PdResult.Fail("新增失败：" + e.getMessage());
        } finally {
            sqLiteOpenHelper.endTransaction();// 结束事务
            semaphore.release();
        }
    }


    /**
     * ------------------------------------------增加结束---------------------------------------------
     */


    /**
     * ------------------------------------------修改开始---------------------------------------------
     */

    /**
     * 修改数据
     *
     * @param dbName
     * @param values
     * @param whereClause      如：id = ?
     * @param whereArgs        如：new String[]{"123"}
     * @param sqLiteOpenHelper
     * @return
     */
    public PdResult modifyDb(SQLiteDatabase sqLiteOpenHelper, String dbName, ContentValues values, String whereClause, String[] whereArgs) {
        try {
            semaphore.acquire();
        } catch (InterruptedException e) {
            e.printStackTrace();
            return PdResult.Fail("修改失败：" + e.getMessage());
        }
        sqLiteOpenHelper.beginTransaction();
        try {
            int update = sqLiteOpenHelper.update(dbName, values, whereClause, whereArgs);
            if (update > 0) {
                sqLiteOpenHelper.setTransactionSuccessful();// 标记事务成功
                //记录日志
                updateLog(dbName, values, whereClause, whereArgs, sqLiteOpenHelper);
                return PdResult.success();
            } else {
                //抛出异常回滚事务
                return PdResult.Fail("修改失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return PdResult.Fail("修改失败：" + e.getMessage());
        } finally {
            sqLiteOpenHelper.endTransaction();// 结束事务
            semaphore.release();
        }
    }
    /**
     * ------------------------------------------修改结束---------------------------------------------
     */
    /**
     * ------------------------------------------删除开始---------------------------------------------
     */


    /**
     * 删除数据
     *
     * @param dbName
     * @param whereClause
     * @param whereArgs
     * @param sqLiteOpenHelper
     * @return
     */
    public PdResult removeDb(SQLiteDatabase sqLiteOpenHelper, String dbName, String whereClause, String[] whereArgs) {
        try {
            semaphore.acquire();
        } catch (InterruptedException e) {
            e.printStackTrace();
            return PdResult.Fail("删除失败：" + e.getMessage());
        }
        sqLiteOpenHelper.beginTransaction();
        try {
            int update = sqLiteOpenHelper.delete(dbName, whereClause, whereArgs);
            if (update > 0) {
                sqLiteOpenHelper.setTransactionSuccessful();// 标记事务成功

                //记录日志
                deleteLog(dbName, whereClause, whereArgs, sqLiteOpenHelper);

                return PdResult.success();
            } else {
                //抛出异常回滚事务
                return PdResult.Fail("删除失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return PdResult.Fail("删除失败：" + e.getMessage());
        } finally {
            sqLiteOpenHelper.endTransaction();// 结束事务
            semaphore.release();
        }
    }

    /**
     * ------------------------------------------删除结束---------------------------------------------
     */

    /**
     * ------------------------------------------查询开始---------------------------------------------
     */

    /**
     * 查询所有
     *
     * @param sqLiteOpenHelper
     * @param dbName
     * @param clazz
     * @param
     * @return
     */
    public <T> PdResult<List<T>> searchDb(SQLiteDatabase sqLiteOpenHelper, String dbName, Class<T> clazz) {

        try {
            semaphore.acquire();
        } catch (InterruptedException e) {
            e.printStackTrace();
            return PdResult.Fail("查询失败，获取semaphore异常");
        }
        List<T> list = new ArrayList<>();
        try {
            String search = search(clazz);
            if (search == null) {
                return PdResult.Fail("查询失败，成员变量获取异常");
            }
            if (search.contains(",")) {
                String sql = "select " + search + " from " + dbName;
                Cursor cursor = sqLiteOpenHelper.rawQuery(sql, null);
                if (cursor.moveToFirst()) {
                    do {
                        T t = (T) setClassVaue(clazz, cursor);
                        if (t != null) {
                            list.add(t);
                        }
                    } while (cursor.moveToNext());
                } else {
                    return PdResult.Fail("传入对象异常，无法找到对象中的成员变量");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            semaphore.release();
        }

        return PdResult.success("查询成功", list);
    }

    /**
     * 查询所有，通过注解
     *
     * @param sqLiteOpenHelper
     * @param clazz            查询的实体
     * @param <T>
     * @return
     */
    public <T> PdResult<List<T>> searchDb(SQLiteDatabase sqLiteOpenHelper, Class<T> clazz) {
        try {
            semaphore.acquire();
        } catch (InterruptedException e) {
            e.printStackTrace();
            return PdResult.Fail("查询失败，获取semaphore异常");
        }
        List<T> list = new ArrayList<>();
        try {
            //获取表名
            String tableName = getTableName(clazz);
            if (tableName == null) {
                return PdResult.Fail("查询失败，获取tableName异常");
            }
            //获取表字段和字段类型
            Map<String, Class<?>> tableFields = getTableFields(clazz);
            String fields = getFields(tableFields);
            if (tableFields.size() == 0) {
                return PdResult.Fail("查询失败，表字段获取异常");
            }
            if (fields.contains(",")) {
                String sql = "select " + fields + " from " + tableName;
                Cursor cursor = sqLiteOpenHelper.rawQuery(sql, null);
                if (cursor.moveToFirst()) {
                    do {
                        T t = (T) setClassVaue(tableFields, clazz, cursor);
                        if (t != null) {
                            list.add(t);
                        }
                    } while (cursor.moveToNext());
                } else {
                    return PdResult.Fail("传入对象异常，无法找到对象中的成员变量");
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            semaphore.release();
        }
        return PdResult.success("查询成功", list);
    }


    /**
     * 通过条件查询单条数据
     *
     * @param sqLiteOpenHelper
     * @param dbName
     * @param where
     * @param params
     * @param clazz
     * @param <T>
     * @return
     */
    public <T> PdResult<T> searDbOneByWhere(SQLiteDatabase sqLiteOpenHelper, String dbName, String where, String[] params, Class<T> clazz) {
        try {
            semaphore.acquire();
        } catch (InterruptedException e) {
            e.printStackTrace();
            return PdResult.Fail("查询失败，获取semaphore异常");
        }
        if (where == null || "".equalsIgnoreCase(where)) {
            semaphore.release();
            return PdResult.Fail("查询失败，where条件不能为空");
        }
        T t = null;
        try {
            String search = search(clazz);
            if (search == null) {
                return PdResult.Fail("查询失败，成员变量获取异常");
            }
            if (search.contains(",")) {
                String sql = "select " + search + " from " + dbName;
                if (where.contains("?")) {
                    sql += " where " + where;
                }
                Cursor cursor = sqLiteOpenHelper.rawQuery(sql, params);
                if (cursor.moveToFirst()) {
                    do {
                        t = setClassVaue(clazz, cursor);
                    } while (cursor.moveToNext());
                } else {
                    return PdResult.Fail("未查询到数据，请检查查询参数是否正确");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return PdResult.Fail("查询失败，数据赋值异常");
        } finally {
            semaphore.release();
        }
        return PdResult.success("查询成功", t);
    }


    /**
     * 通过条件查询多条信息
     *
     * @param sqLiteOpenHelper
     * @param dbName
     * @param where
     * @param params
     * @param clazz
     * @param <T>
     * @return
     */
    public <T> PdResult<List<T>> searDbByWhere(SQLiteDatabase sqLiteOpenHelper, String dbName, String where, String[] params, Class<T> clazz) {
        try {
            semaphore.acquire();
        } catch (InterruptedException e) {
            e.printStackTrace();
            return PdResult.Fail("查询失败，获取semaphore异常");
        }
        if (where == null || "".equalsIgnoreCase(where)) {
            semaphore.release();
            return PdResult.Fail("查询失败，where条件不能为空");
        }
        List<T> list = new ArrayList<>();
        try {
            String search = search(clazz);
            if (search == null) {
                return PdResult.Fail("查询失败，成员变量获取异常");
            }
            if (search.contains(",")) {
                String sql = "select " + search + " from " + dbName;
                if (where.contains("?")) {
                    sql += " where " + where;
                }
                Cursor cursor = sqLiteOpenHelper.rawQuery(sql, params);
                if (cursor.moveToFirst()) {
                    do {
                        T t = (T) setClassVaue(clazz, cursor);
                        if (t != null) {
                            list.add(t);
                        }
                    } while (cursor.moveToNext());
                } else {
                    return PdResult.Fail("未查询到数据，请检查查询参数是否正确");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return PdResult.Fail("查询失败，数据赋值异常");
        } finally {
            semaphore.release();
        }
        return PdResult.success("查询成功", list);
    }

    /**
     * 注解查询单条信息
     *
     * @param sqLiteOpenHelper
     * @param where
     * @param params
     * @param clazz
     * @param <T>
     * @return
     */
    public <T> PdResult<T> searDbOneByWhere(SQLiteDatabase sqLiteOpenHelper, String where, String[] params, Class<T> clazz) {
        try {
            semaphore.acquire();
        } catch (InterruptedException e) {
            e.printStackTrace();
            return PdResult.Fail("查询失败，获取semaphore异常");
        }
        if (where == null || "".equalsIgnoreCase(where)) {
            semaphore.release();
            return PdResult.Fail("查询失败，where条件不能为空");
        }
        T t = null;
        try {

            //获取表名
            String tableName = getTableName(clazz);
            if (tableName == null) {
                return PdResult.Fail("查询失败，获取tableName异常");
            }
            //获取表字段和字段类型
            Map<String, Class<?>> tableFields = getTableFields(clazz);
            String fields = getFields(tableFields);
            if (tableFields.size() == 0) {
                return PdResult.Fail("查询失败，表字段获取异常");
            }
            if (fields.contains(",")) {
                String sql = "select " + fields + " from " + tableName;
                if (where.contains("?")) {
                    sql += " where " + where;
                }
                Cursor cursor = sqLiteOpenHelper.rawQuery(sql, params);
                if (cursor.moveToFirst()) {
                    do {
                        t = setClassVaue(tableFields, clazz, cursor);
                    } while (cursor.moveToNext());
                } else {
                    return PdResult.Fail("未查询到数据，请检查查询参数是否正确");
                }
            }

        } catch (Exception e) {

        } finally {
            semaphore.release();
        }
        return PdResult.success("查询成功", t);
    }


    /**
     * 注解条件查询多条信息
     *
     * @param sqLiteOpenHelper
     * @param where
     * @param params
     * @param clazz
     * @param <T>
     * @return
     */
    public <T> PdResult<List<T>> searDbByWhere(SQLiteDatabase sqLiteOpenHelper, String where, String[] params, Class<T> clazz) {
        try {
            semaphore.acquire();
        } catch (InterruptedException e) {
            e.printStackTrace();
            return PdResult.Fail("查询失败，获取semaphore异常");
        }
        if (where == null || "".equalsIgnoreCase(where)) {
            semaphore.release();
            return PdResult.Fail("查询失败，where条件不能为空");
        }
        List<T> list = new ArrayList<>();
        try {

            //获取表名
            String tableName = getTableName(clazz);
            if (tableName == null) {
                return PdResult.Fail("查询失败，获取tableName异常");
            }
            //获取表字段和字段类型
            Map<String, Class<?>> tableFields = getTableFields(clazz);
            String fields = getFields(tableFields);
            if (tableFields.size() == 0) {
                return PdResult.Fail("查询失败，表字段获取异常");
            }
            if (fields.contains(",")) {
                String sql = "select " + fields + " from " + tableName;
                if (where.contains("?")) {
                    sql += " where " + where;
                }
                Cursor cursor = sqLiteOpenHelper.rawQuery(sql, params);
                if (cursor.moveToFirst()) {
                    do {
                        T t = (T) setClassVaue(tableFields, clazz, cursor);
                        if (t != null) {
                            list.add(t);
                        }
                    } while (cursor.moveToNext());
                } else {
                    return PdResult.Fail("未查询到数据，请检查查询参数是否正确");
                }
            }

        } catch (Exception e) {

        } finally {
            semaphore.release();
        }
        return PdResult.success("查询成功", list);
    }

    /**
     * 有参查询总数
     *
     * @param sqLiteOpenHelper
     * @param dbName
     * @param where
     * @param params
     * @return
     */
    public PdResult<Integer> searchDbCount(SQLiteDatabase sqLiteOpenHelper, String dbName, String where, String[] params) {
        try {
            semaphore.acquire();
        } catch (InterruptedException e) {
            e.printStackTrace();
            return PdResult.Fail("查询失败，获取semaphore异常");
        }
        Integer count = 0;
        try {
            String sql = "select count(*) count from " + dbName;
            if (where != null && !"".equalsIgnoreCase(where)) {
                sql += " where " + where;
            }
            Cursor cursor = sqLiteOpenHelper.rawQuery(sql, null);
            if (params != null && params.length > 0) {
                cursor = sqLiteOpenHelper.rawQuery(sql, params);
            }
            if (cursor.moveToFirst()) {
                do {
                    count = cursor.getInt(cursor.getColumnIndex("count"));
                } while (cursor.moveToNext());
            } else {
                return PdResult.Fail("传入对象异常，无法找到对象中的成员变量");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return PdResult.Fail("查询失败，数据赋值异常");
        } finally {
            semaphore.release();
        }
        return PdResult.success("查询成功", count);
    }


    /**
     * 无参查询总数
     *
     * @param sqLiteOpenHelper
     * @param dbName
     * @return
     */
    public PdResult<Integer> searchDbCount(SQLiteDatabase sqLiteOpenHelper, String dbName) {
        try {
            semaphore.acquire();
        } catch (InterruptedException e) {
            e.printStackTrace();
            return PdResult.Fail("查询失败，获取semaphore异常");
        }
        Integer count = 0;
        try {
            String sql = "select count(*) count from " + dbName;
            Cursor cursor = sqLiteOpenHelper.rawQuery(sql, null);
            if (cursor.moveToFirst()) {
                do {
                    count = cursor.getInt(cursor.getColumnIndex("count"));
                } while (cursor.moveToNext());
            } else {
                return PdResult.Fail("传入对象异常，无法找到对象中的成员变量");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return PdResult.Fail("查询失败，数据赋值异常");
        } finally {
            semaphore.release();
        }
        return PdResult.success("查询成功", count);
    }


    /**
     * 有参查询字段field最大值
     *
     * @param sqLiteOpenHelper
     * @param dbName
     * @param field
     * @param where
     * @param params
     * @return
     */
    public PdResult<Integer> searchDbMax(SQLiteDatabase sqLiteOpenHelper, String dbName, String field, String where, String[] params) {
        try {
            semaphore.acquire();
        } catch (InterruptedException e) {
            e.printStackTrace();
            return PdResult.Fail("查询失败，获取semaphore异常");
        }
        Integer count = 0;
        try {
            String sql = "select max(" + field + ") count from " + dbName;
            if (where != null && !"".equalsIgnoreCase(where)) {
                sql += " where " + where;
            }
            Cursor cursor = sqLiteOpenHelper.rawQuery(sql, null);
            if (params != null && params.length > 0) {
                cursor = sqLiteOpenHelper.rawQuery(sql, params);
            }
            if (cursor.moveToFirst()) {
                do {
                    count = cursor.getInt(cursor.getColumnIndex("count"));
                } while (cursor.moveToNext());
            } else {
                return PdResult.Fail("传入对象异常，无法找到对象中的成员变量");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return PdResult.Fail("查询失败，数据赋值异常");
        } finally {
            semaphore.release();
        }
        return PdResult.success("查询成功", count);
    }


    /**
     * 无参查询字段field最大值
     *
     * @param sqLiteOpenHelper
     * @param dbName
     * @param field
     * @return
     */
    public PdResult<Integer> searchDbMax(SQLiteDatabase sqLiteOpenHelper, String dbName, String field) {
        try {
            semaphore.acquire();
        } catch (InterruptedException e) {
            e.printStackTrace();
            return PdResult.Fail("查询失败，获取semaphore异常");
        }
        Integer count = 0;
        try {
            String sql = "select max(" + field + ") count from " + dbName;
            Cursor cursor = sqLiteOpenHelper.rawQuery(sql, null);
            if (cursor.moveToFirst()) {
                do {
                    count = cursor.getInt(cursor.getColumnIndex("count"));
                } while (cursor.moveToNext());
            } else {
                return PdResult.Fail("传入对象异常，无法找到对象中的成员变量");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return PdResult.Fail("查询失败，数据赋值异常");
        } finally {
            semaphore.release();
        }
        return PdResult.success("查询成功", count);
    }


    /**
     * 有参查询字段field最小值
     *
     * @param sqLiteOpenHelper
     * @param dbName
     * @param field
     * @param where
     * @param params
     * @return
     */
    public PdResult<Integer> searchDbMin(SQLiteDatabase sqLiteOpenHelper, String dbName, String field, String where, String[] params) {
        try {
            semaphore.acquire();
        } catch (InterruptedException e) {
            e.printStackTrace();
            return PdResult.Fail("查询失败，获取semaphore异常");
        }
        Integer count = 0;
        try {
            String sql = "select min(" + field + ") count from " + dbName;
            if (where != null && !"".equalsIgnoreCase(where)) {
                sql += " where " + where;
            }
            Cursor cursor = sqLiteOpenHelper.rawQuery(sql, null);
            if (params != null && params.length > 0) {
                cursor = sqLiteOpenHelper.rawQuery(sql, params);
            }
            if (cursor.moveToFirst()) {
                do {
                    count = cursor.getInt(cursor.getColumnIndex("count"));
                } while (cursor.moveToNext());
            } else {
                return PdResult.Fail("传入对象异常，无法找到对象中的成员变量");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return PdResult.Fail("查询失败，数据赋值异常");
        } finally {
            semaphore.release();
        }
        return PdResult.success("查询成功", count);
    }


    /**
     * 无参查询字段field最小值
     *
     * @param sqLiteOpenHelper
     * @param dbName
     * @param field
     * @return
     */
    public PdResult<Integer> searchDbMin(SQLiteDatabase sqLiteOpenHelper, String dbName, String field) {
        try {
            semaphore.acquire();
        } catch (InterruptedException e) {
            e.printStackTrace();
            return PdResult.Fail("查询失败，获取semaphore异常");
        }
        Integer count = 0;
        try {
            String sql = "select min(" + field + ") count from " + dbName;
            Cursor cursor = sqLiteOpenHelper.rawQuery(sql, null);
            if (cursor.moveToFirst()) {
                do {
                    count = cursor.getInt(cursor.getColumnIndex("count"));
                } while (cursor.moveToNext());
            } else {
                return PdResult.Fail("传入对象异常，无法找到对象中的成员变量");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return PdResult.Fail("查询失败，数据赋值异常");
        } finally {
            semaphore.release();
        }
        return PdResult.success("查询成功", count);
    }


    /**
     * 获取传入对象的成员变量
     *
     * @return
     */
    private String search(Class clazz) {
        String fieldStr = null;
        try {
            Field[] declaredFields = clazz.getDeclaredFields();
            StringBuilder fields = new StringBuilder();
            for (Field field : declaredFields) {
                if (!field.getName().equals("serialVersionUID")) {
                    fields.append(field.getName()).append(",");
                }
            }
            fieldStr = fields.toString();
            if (fieldStr.endsWith(",")) {
                fieldStr = fieldStr.substring(0, fieldStr.lastIndexOf(","));
            }
        } catch (Exception e) {
            Log.e("获取Class成员变量", "获取传入对象的成员变量：" + e.getMessage());
        }
        return fieldStr;
    }

    /**
     * 给查询的数据赋值授权
     *
     * @param clazz
     * @param cursor
     * @param <T>
     * @return
     */
    private <T> T setClassVaue(Class clazz, Cursor cursor) {
        T t = null;
        try {
            Field[] declaredFields = clazz.getDeclaredFields();
            t = (T) clazz.getDeclaredConstructor().newInstance();
            for (Field field : declaredFields) {
                try {
                    if (!field.getName().equals("serialVersionUID")) {
                        Class<?> fieldType = field.getType();
                        String name = field.getName();
                        Field declaredField = clazz.getDeclaredField(name);
                        declaredField.setAccessible(true);
                        if (fieldType == String.class) {
                            //字符串（String）
                            declaredField.set(t, cursor.getString(cursor.getColumnIndex(name)));
                        } else if (fieldType == Integer.class) {
                            //整数（Integer）
                            declaredField.set(t, cursor.getInt(cursor.getColumnIndex(name)));
                        } else if (fieldType == Long.class) {
                            //长整型（Long）
                            declaredField.set(t, cursor.getLong(cursor.getColumnIndex(name)));
                        } else if (fieldType == Float.class) {
                            //浮点数（Float）
                            declaredField.set(t, cursor.getFloat(cursor.getColumnIndex(name)));
                        } else if (fieldType == Double.class) {
                            //双精度浮点数（Double）
                            declaredField.set(t, cursor.getDouble(cursor.getColumnIndex(name)));
                        } else if (fieldType == Short.class) {
                            //短整型（Short）
                            declaredField.set(t, cursor.getShort(cursor.getColumnIndex(name)));
                        } else if (fieldType == Byte.class) {
                            //字节（Byte）
                            declaredField.set(t, cursor.getBlob(cursor.getColumnIndex(name)));
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            return t;
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("Class成员变量赋值", "Class成员变量赋值：" + e.getMessage());
        }
        return null;
    }

    /**
     * ------------------------------------------查询结束---------------------------------------------
     */


    // 获取表名
    private String getTableName(Class<?> clazz) {
        TableName tableName = clazz.getAnnotation(TableName.class);
        return tableName != null ? tableName.value() : null;
    }

    // 获取表字段信息
    private Map<String, Class<?>> getTableFields(Class<?> clazz) {
        Field[] fields = clazz.getDeclaredFields();
        Map<String, Class<?>> map = new HashMap<>();
        for (Field field : fields) {
            if (field.isAnnotationPresent(IgnoreField.class)) {
                continue; // 忽略标记为 IgnoreField 的字段
            }
            if (field.getName().equals("serialVersionUID")) {
                continue; // 忽略标记为 IgnoreField 的字段
            }
            TableField tableField = field.getAnnotation(TableField.class);
            String fieldName = tableField != null && !tableField.value().isEmpty() ? tableField.value() : field.getName();
            String fieldType = field.getType().getName();
            System.out.println("字段名: " + fieldName + ", 字段类型: " + fieldType);
            map.put(fieldName, field.getType());
        }
        return map;
    }

    //获取需要查询的字段
    private String getFields(Map<String, Class<?>> map) {
        String fieldStr = null;
        StringBuilder fields = new StringBuilder();
        for (Map.Entry<String, Class<?>> m : map.entrySet()) {
            fields.append(m.getKey()).append(",");
        }
        fieldStr = fields.toString();
        if (fieldStr.endsWith(",")) {
            fieldStr = fieldStr.substring(0, fieldStr.lastIndexOf(","));
        }
        return fieldStr;
    }


    private <T> T setClassVaue(Map<String, Class<?>> tableFields, Class clazz, Cursor cursor) {

        T t = null;
        try {
            t = (T) clazz.getDeclaredConstructor().newInstance();

            // 获取所有字段，建立数据库字段名到Java字段的映射
            Field[] declaredFields = clazz.getDeclaredFields();
            Map<String, Field> fieldMap = new HashMap<>();

            for (Field field : declaredFields) {
                if (field.isAnnotationPresent(IgnoreField.class)) {
                    continue;
                }
                if (field.getName().equals("serialVersionUID")) {
                    continue;
                }

                TableField tableField = field.getAnnotation(TableField.class);
                String dbFieldName;
                if (tableField != null && !tableField.value().isEmpty()) {
                    dbFieldName = tableField.value(); // 数据库字段名
                } else {
                    dbFieldName = field.getName(); // 如果没有注解，使用属性名
                }
                fieldMap.put(dbFieldName, field);
            }

            for (Map.Entry<String, Class<?>> map : tableFields.entrySet()) {
                String dbFieldName = map.getKey();
                Field field = fieldMap.get(dbFieldName);

                if (field == null) {
                    continue; // 如果找不到对应的字段，跳过
                }

                field.setAccessible(true);
                int columnIndex = cursor.getColumnIndex(dbFieldName);

                if (columnIndex == -1) {
                    continue; // 如果游标中没有该列，跳过
                }

                Class<?> fieldType = field.getType();

                if (fieldType == String.class) {
                    field.set(t, cursor.getString(columnIndex));
                } else if (fieldType == Integer.class || fieldType == int.class) {
                    field.set(t, cursor.getInt(columnIndex));
                } else if (fieldType == Long.class || fieldType == long.class) {
                    field.set(t, cursor.getLong(columnIndex));
                } else if (fieldType == Float.class || fieldType == float.class) {
                    field.set(t, cursor.getFloat(columnIndex));
                } else if (fieldType == Double.class || fieldType == double.class) {
                    field.set(t, cursor.getDouble(columnIndex));
                } else if (fieldType == Short.class || fieldType == short.class) {
                    field.set(t, cursor.getShort(columnIndex));
                } else if (fieldType == Byte.class || fieldType == byte.class) {
                    field.set(t, cursor.getBlob(columnIndex));
                } else if (fieldType == Boolean.class || fieldType == boolean.class) {
                    int value = cursor.getInt(columnIndex);
                    field.set(t, value == 1);
                }
            }
            return t;
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("Class成员变量赋值", "Class成员变量赋值：" + e.getMessage());
        }
        return null;
    }


    //处理记录删除日志
    private void deleteLog(String dbName, String whereClause, String[] whereArgs, SQLiteDatabase sqLiteOpenHelper) {
        try {
            String deleteSql = "delete from " + dbName;
            if (whereClause != null && whereClause.contains("?")) {
                deleteSql += " where ";
                String[] split = whereClause.split("\\?");
                for (int i = 0; i < split.length; i++) {
                    if (!"".equalsIgnoreCase(split[i].trim())) {
                        deleteSql += split[i] + "'" + whereArgs[i] + "'";
                    }
                }
            }
            logOperation(deleteSql, sqLiteOpenHelper, "delete");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //处理记录修改日志
    private void updateLog(String dbName, ContentValues values, String whereClause, String[] whereArgs, SQLiteDatabase sqLiteOpenHelper) {
        try {
            String updateSql = "UPDATE " + dbName + " set ";
            for (String key : values.keySet()) {
                Object value = values.get(key);
                System.out.println("Key: " + key + ", Value: " + value);
                updateSql += key + "='" + value + "'";
            }

            if (whereClause != null && whereClause.contains("?")) {
                updateSql += " where ";
                String[] split = whereClause.split("\\?");
                for (int i = 0; i < split.length; i++) {
                    if (!"".equalsIgnoreCase(split[i].trim())) {
                        updateSql += split[i] + "'" + whereArgs[i] + "'";
                    }
                }
            }

            logOperation(updateSql, sqLiteOpenHelper, "update");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //处理记录新增日志
    private void addLog(ContentValues contentValues, SQLiteDatabase sqLiteOpenHelper, String dbName) {
        try {
            String tableFields = "";
            String tableValue = "";
            for (String key : contentValues.keySet()) {
                Object value = contentValues.get(key);
                tableFields += key + ",";
                tableValue += "'" + value + "',";
            }
            tableFields = tableFields.substring(0, tableFields.length() - 1);
            tableValue = tableValue.substring(0, tableValue.length() - 1);
            String addSql = "INSERT INTO " + dbName + " ( " + tableFields + ") values (" + tableValue + ");";
            logOperation(addSql, sqLiteOpenHelper, "add");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 记录增加、修改、删除的数据
     *
     * @param sql              执行的sql
     * @param sqLiteOpenHelper 数据库唯一值
     * @param type
     */
    private void logOperation(String sql, SQLiteDatabase sqLiteOpenHelper, String type) {
        if (!logTarget) {
            return;
        }
        FileOutputStream fos = null;
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss", Locale.getDefault());
            String timestamp = sdf.format(new Date());
            String logEntry = timestamp + "-" + PdMethod.md5(sqLiteOpenHelper.getPath()) + "-" + type + "-" + sql + "\n";
            File externalDir = new File(Environment.getExternalStorageDirectory() + "/pdlogs");
            if (!externalDir.exists()) {
                externalDir.mkdirs();
            }
            File logFile = new File(externalDir, super.dbLogName);
            fos = new FileOutputStream(logFile, true);
            fos.write(logEntry.getBytes());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }


    //db数据恢复
    @RequiresApi(api = Build.VERSION_CODES.O)
    public void rebackData(SQLiteDatabase sqLiteOpenHelper, String beginTime, String endTime) {
        rebackDataFromLog(sqLiteOpenHelper, beginTime, endTime);
    }

    //db数据恢复
    @RequiresApi(api = Build.VERSION_CODES.O)
    public void rebackData(SQLiteDatabase sqLiteOpenHelper) {
        rebackDataFromLog(sqLiteOpenHelper, null, null);
    }


    public boolean rebackDbDataSrarus = false;

    /**
     * db数据库恢复，读取日志恢复数据
     *
     * @param sqLiteOpenHelper
     * @param beginTime        yyyy/MM/dd HH:mm:ss
     * @param endTime          yyyy/MM/dd HH:mm:ss
     */
    @RequiresApi(api = Build.VERSION_CODES.O)
    private void rebackDataFromLog(SQLiteDatabase sqLiteOpenHelper, String beginTime, String endTime) {
        try {
            rebackDbDataSrarus = false;
            File externalDir = Environment.getExternalStorageDirectory();
            File logFile = new File(externalDir, super.dbLogName);
            if (logFile.exists()) {
                java.util.Scanner scanner = new java.util.Scanner(logFile);
                String path = sqLiteOpenHelper.getPath();
                String s1 = PdMethod.md5(path);

                while (scanner.hasNextLine()) {
                    try {
                        String line = scanner.nextLine();
                        String[] split = line.split("-");
                        boolean target = true;
                        String trim = split[0].trim();
                        long lg = convertToLong(trim);
                        if (beginTime != null) {
                            long beginLg = convertToLong(beginTime);
                            if (lg < beginLg) {
                                target = false;
                            }
                        }
                        if (endTime != null) {
                            long endlg = convertToLong(endTime);
                            if (lg > endlg) {
                                target = false;
                            }
                        }
                        if (split[1].trim().equalsIgnoreCase(s1) && target) {
                            String s = split[split.length - 1];
                            try {
                                semaphore.acquire();
                                sqLiteOpenHelper.execSQL(s);
                            } catch (Exception e) {
                                e.printStackTrace();
                            } finally {
                                semaphore.release();
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                scanner.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            rebackDbDataSrarus = true;
        }
    }


    //清楚数据库备份
    public void cleanBack() {
        try {
            File externalDir = Environment.getExternalStorageDirectory();
            File file = new File(externalDir, super.dbLogName);
            if (file.isFile() && file.exists()) {
                file.delete();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @RequiresApi(api = Build.VERSION_CODES.O)
    private long convertToLong(String timestampStr) {
        String format = "yyyy/MM/dd HH:mm:ss";
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(format);
        LocalDateTime dateTime = LocalDateTime.parse(timestampStr, formatter);
        return dateTime.toInstant(ZoneOffset.UTC).toEpochMilli();
    }
}
